<?php

namespace Model;

class Database {
	
        private $mysqli = NULL;
        
        public function Connect(DBConfig $config) {
            	
            $this->mysqli = new \mysqli($config->m_host, 
                                                     $config->m_user, 
                                                     $config->m_pass, 
                                                     $config->m_db);

            
            if ($this->mysqli->connect_error) {
                throw new \Exception($this->mysqli->connect_error);
            }
            
            $this->mysqli->set_charset("utf8");
            
            return true;
        }
		
		public function Prepare($sql) {
           
		    $ret = $this->mysqli->prepare($sql);
            
            if ($ret == FALSE) {
                    throw new \Exception($this->mysqli->error);
            }
            
            return $ret;
                
        }
		
		public function RunInsertQuery(\mysqli_stmt $stmt){
			
			if($stmt->execute()==FALSE){
				throw new \Exception($this->mysqli->error);
			}
			
			$ret = $stmt->insert_id;
			
			$stmt->close();
			
			return $ret;
		}
		
		public function Select($sqlQuery) {
                
               
            $stmt = $this->mysqli->prepare($sqlQuery);
            
            if ($stmt === FALSE) {
                    throw new \Exception($this->mysqli->error);
            }
         
            if ($stmt->execute() == FALSE) {
                    throw new \Exception($this->mysqli->error);
            }
            $ret = 0;
            
            return $stmt;
        }
		
		public function Close() {
                return $this->mysqli->close();
        }
		
       public static function test(DBConfig $dbConfig) {
            	
            $db = new Database();
            
            if ($db->Connect($dbConfig) == false) {
                    echo "Fel vid anslutning till datbasen";
                    return false;
            }
            
            if ($db->Close() == false) {
                    echo "Fel vid stängning av databas";
                    return false;
            }
            
            
            return true;
        }       
}
